import json

from django.shortcuts import render
from django.http import HttpResponse
import uuid
from django.http import JsonResponse
from django.views import View

# Create your views here.


from rest_framework.views import APIView
from rest_framework.response import Response
from auth_app import models
from auth_app.utils.jwt_auth import create_token
from tools.connect_mysql import MysqlConnect

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, InvalidPage


class LoginView(APIView):
    authentication_classes = []  # 优先级更高（为了防止登录页面不停验证产生死循环）

    def post(self, request, *args, **kwargs):
        user = request.data.get('username')
        pwd = request.data.get('password')
        # 过滤数据库中数据，如果有对应的数据则返回第一个
        user_object = models.UserInfo.objects.filter(username=user, password=pwd).first()
        # 如果没有找到，就返回错误信息
        if not user_object:
            return Response({'code': 1000, 'error': '用户名或密码错误'})
        token = create_token({'user_id': user_object.id, 'username': user_object.username})
        return Response({'code': 10001, 'token': token})


class OrderView(APIView):
    # authentication_classes = [JwtQueryParamsAuthentication, ]

    def get(self, request, *args, **kwargs):
        print(request.user)
        print(request.auth)
        return Response('鉴权成功')


from config.menu_config import data


class Menus(APIView):

    def get(self, request, *args, **kwargs):
        # 获取菜单列表
        menu_data = {
            # "data": list(models.Menu.objects.all().values()),
            "data": data,
            "meta": {
                "msg": "获取菜单列表成功",
                "status": 200
            }}
        # print(menu_data)
        return JsonResponse(menu_data, json_dumps_params={'ensure_ascii': False})


class UserList(APIView):

    # 用户列表接口
    def get(self, request, *args, **kwargs):
        """

        :param request: 包含三个参数
        query 查询条件
        pagennum 获取页码
        pagesizi 每页条数
        :return:
        """

        if request.GET["query"] == "":
            data_list = models.UserInfo.objects.all()
        else:
            data_list = models.UserInfo.objects.filter(email__contains=request.GET["query"])

        data_count = data_list.count()  # 获取数据总条数

        page_num = int(request.GET["pagennum"])  # 获取页码
        page_size = int(request.GET["pagesizi"])  # 每页条数
        start_page = (page_num - 1) * page_size  # 开始数据
        end_page = page_num * page_size  # 结束数据

        data_list = list(data_list[start_page:end_page].values())

        get_user = {
            # "data": list(models.Menu.objects.all().values()),
            "data": data_list,
            "total": data_count,
            "meta": {
                "msg": "获取用户列表成功",
                "status": 200
            }}
        return JsonResponse(get_user)


class User(APIView):

    # 用户列表接口
    def get(self, request, *args, **kwargs):
        """

        :param request: 包含三个参数
        query 查询条件
        pagennum 获取页码
        pagesizi 每页条数
        :return:
        """
        user_data = models.UserInfo.objects.filter(id=request.GET["id"])
        get_user = {
            # "data": list(models.Menu.objects.all().values()),
            "data": list(user_data.values())[0],
            # "total": data_count,
            "meta": {
                "msg": "获取用户列表成功",
                "status": 200
            }}
        return JsonResponse(get_user)

    # 修改用户状态
    def put(self, request, *args, **kwargs):
        """
        如果用户
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        request_data = json.loads(request.body)
        id = request_data.get('id')
        if request_data.get('role_name') == "超级管理员":
            meta = {"msg": "超级管理员信息不可修改", "status": 201}
        else:
            if request_data.get('email') is None:
                mg_state = request_data.get('mg_state')
                models.UserInfo.objects.filter(id=id).update(mg_state=mg_state)
            else:
                email = request_data.get('email')
                username = request_data.get('username')
                password = request_data.get('password')
                mobile = request_data.get('mobile')
                models.UserInfo.objects.filter(id=id).update(email=email, username=username, password=password,
                                                             mobile=mobile)
            meta = {"msg": "修改用户状态成功", "status": 200}

        update_user = {"meta": meta}
        return JsonResponse(update_user)

    # 新增用户数据
    def post(self, request, *args, **kwargs):
        request_data = json.loads(request.body)
        # print(request_data)
        if models.UserInfo.objects.filter(email__exact=request_data["email"]):
            meta = {
                "msg": "用户已存在,请误重复添加",
                "status": 201
            }
        else:
            models.UserInfo.objects.create(
                email=request_data["email"],
                username=request_data["username"],
                password=request_data["password"],
                mobile=request_data["phone"],
                mg_state=1)
            meta = {
                "msg": "新增用户成功",
                "status": 200
            }

        add_user = {"meta": meta}
        return JsonResponse(add_user)

    # 删除用户数据
    def delete(self, request, *args, **kwargs):
        # print(request.GET["id"])

        # request_data = json.loads(request.body)
        # print(request_data)
        id = request.GET["id"]
        # if request.GET('role_name') == "超级管理员":
        #     meta = {"msg": "超级管理员信息不可修改", "status": 201}
        # else:
        models.UserInfo.objects.filter(id=id).delete()
        meta = {"msg": "删除用户信息成功", "status": 200}

        delete_user = {"meta": meta}
        return JsonResponse(delete_user)
